/**
 * @description 触底加载更多容器
 */
import React from 'react';
import classnames from "classnames";
import "./styles/App.less";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
    this.wrapperRef = React.createRef();
    this.containerRef = React.createRef();
    this.canRunReachEnd = true; // 节流标记
  }

  componentDidMount() {
    // 添加滚动监听
    this.containerRef.current.addEventListener("scroll", this.onScroll.bind(this));
  }
  componentWillUnmount() {
    // 移除滚动监听
    this.containerRef.current.removeEventListener("scroll", this.onScroll);
  }

  render() {
    return (
      <div className={classnames(this.props.className, {
        ["x-scrollReachEndContainer"]: !this.props.className,
        ["x-scrollReachEndContainer-noScroll"]: !this.props.canScroll
      })} ref={this.containerRef}>
        <div ref={this.wrapperRef}>
          {
            this.props.children
          }
          {
            !!this.props.showScrollLoadText && <div className="x-scrollReachEndContainer-loadtext"><span>{this.props.loadText}</span></div>
          }
        </div>
      </div>
    );
  }

  // 滚动监听
  onScroll() {
    if(!this.props.canScroll){
      return;
    }

    const scrollTop = this.containerRef.current.scrollTop;
    const containerHeight = this.containerRef.current.offsetHeight;
    const scrollHeight = this.containerRef.current.scrollHeight;

    // 容器高+滚动距离 > 滚动高度（容器高+最大滚动距离）- 阈值, 判定为触底
    if (containerHeight + scrollTop >= scrollHeight - this.props.threshold) {
      if (this.props.throttleTime > 0) {
        // 如果节流时间大于0
        this.throttle(this.props.onReachEnd);
      } else {
        // 如果节流时间等于0，则立即执行
        this.props.onReachEnd();
      }
    }
    // 滚动高度回调
    this.props.onScroll && this.props.onScroll(this.containerRef.current.scrollTop);
  }

  // 节流
  throttle(fn) {
    if (!this.canRunReachEnd) {
      return false;
    }
    fn();
    this.canRunReachEnd = false;
    setTimeout(() => {
      this.canRunReachEnd = true;
    }, this.props.throttleTime);
  }
}

App.defaultProps = {
  // 触底阈值，单位像素
  threshold: 0,
  // 加载文案
  loadText: "正在加载更多",
  // 触底函数
  onReachEnd: () => { },
  // 显示底部分案
  showScrollLoadText: true,
  // 滚动触发
  onScroll: null,
  // 节流时间
  throttleTime: 1000,
  // 能否滚动
  canScroll: true
};

export default App;
